<template>
    <div class="pages">
      <canvas style="width: 250px;height:250px;background:#fff;position: absolute;top:1000000px;left:0;" canvas-id="shareFrends" ></canvas>
      <div class="imgBox">
        <p>专属名片小程序码</p>
        <img :src="userInfo.avatarUrl" alt="" class="header">
        <img :src="codeImg" alt="" class="codeImg">
      </div>
      <button  class="weui-btn weui-btn_primary" @click=" canvasToImage()">保存小程序码到手机</button>
<!--      -->
<!--      <div class="share_tips" @click="canvasToImage()">点击保存图片</div>-->
    </div>
</template>

<script>
     import { base64src  } from '../../utils/base64.js'
     import * as host from "../../utils/api"
    export default {
        name: "index",
        data(){
            return{
                userInfo:{},
                urlCode:"",
                qrcodeUrl:"",
                codeImg:"",
                wxImgCode:""
            }
        },
        onShow(){
          wx.setNavigationBarTitle({
            title: '专属名片'
          })
            this.userInfo=JSON.parse(JSON.parse(wx.getStorageSync('userInfo')))
         // this.createdCode()
           this.getCode()

          // 上传文件
            this.codeImg=  wx.getStorageSync('flag2');

        },
        onReady(){
          this.codeImg=  wx.getStorageSync('flag2');

        },
        methods:{
            getCode(){
                let that=this;
              let Authorization= wx.getStorageSync('Authorization')
              let cartId=wx.getStorageSync('cartId')
              let userId= wx.getStorageSync('userId')
              this.$http.request({
                  url:"/api/WxCode/unlimitCreate",
                  method:"get",

                  body:{
                      scene:`${cartId}&${userId}&2`,
                      page:"pages/index/main",
                      width:250,
                    cardId:wx.getStorageSync('cartId')
                  }
              }).then((res)=>{
                  if(res.code==200){
                     this.codeImg=res.data;
                    this.createdCode();
                  }

              })
            },
            getPromise(url){
              return new Promise((resolve, reject) => {
                  wx.downloadFile({
                      url:url ,
                      success (res) {
                       //   console.log(res)
                          resolve(res)
                      }
                  })
              })
            },
            //开始绘图
            createdCode() {
                let that=this;
                var avatarurl_width = 125;    //绘制的头像宽度
                var avatarurl_heigth = 125;   //绘制的头像高度
                var avatarurl_x = 60;   //绘制的头像在画布上的位置
                var avatarurl_y = 66;   //绘制的头像在画布上的位置
                    //console.log(headerImg)
                this.getPromise(that.codeImg).then((data)=>{
                  that.wxImgCode=data.tempFilePath
                  // console.log(that.wxImgCode)


                  this.getPromise(that.userInfo.avatarUrl).then((header)=>{
                    const ctx = wx.createCanvasContext('shareFrends');    //绘图上下文
                    //  console.log(header)
                    ctx.beginPath(); //开始绘制
                     ctx.drawImage(that.wxImgCode,  0, 0, 250, 250);
                      //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
                      ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);

                      ctx.clip();//画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因

                      ctx.drawImage(header.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片，必须是https图片
                    ctx.draw()

                  })


                    })

            },
            canvasToImage() {
                var that = this
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 250,
                    height: 250,
                    destWidth: 500*   wx.getSystemInfoSync().pixelRatio,
                    destHeight:500 *  wx.getSystemInfoSync().pixelRatio,
                    canvasId: 'shareFrends',
                    success: function (res) {
                      //  console.log('朋友圈分享图生成成功:' + res.tempFilePath)
                        wx.saveFile({
                            tempFilePath: res.tempFilePath, // 当前显示图片的http链接
                            success:(data)=>{
                             //   console.log(data)
                                let savedFilePath=data.savedFilePath;
                                that.saveImageToPhotos(savedFilePath)
                            }
                            // urls: [res.tempFilePath] // 需要预览的图片http链接列表
                        })
                    },
                    fail: function (err) {
                        wx.showToast({
                            title: `失败`,
                            icon: 'success',
                            duration: 2000
                        })
                       // console.log(err)
                    }
                },this)
            },

            // 保存图片方法
            saveImage (filePath) {
                wx.saveImageToPhotosAlbum({
                    filePath: filePath,  // 此为图片路径
                    success: (res) => {
                        wx.showToast({
                            title: `保存成功`,
                            icon: 'success',
                            duration: 2000
                        })
                    },
                    fail: (err) => {
                        wx.showToast({
                            title: `保存失败`,
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            },
            // 点击保存图片到相册(授权)
            saveImageToPhotos (filePath) {
                let self = this
                // 相册授权
                wx.getSetting({
                    success(res) {
                        // 进行授权检测，未授权则进行弹层授权
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            wx.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success () {
                                    self.saveImage(filePath)
                                },
                                // 拒绝授权时，则进入手机设置页面，可进行授权设置
                                fail() {
                                    wx.openSetting({
                                        success: function (data) {
                                           // console.log("openSetting success");
                                        },
                                        fail: function (data) {
                                            //console.log("openSetting fail");
                                        }
                                    });
                                }
                            })
                        } else {
                            // 已授权则直接进行保存图片
                            self.saveImage(filePath)
                        }
                    },
                    fail(res) {
                      //  console.log(res);
                    }
                })
            },
            //文字换行处理
            // canvas 标题超出换行处理
            wordsWrap(ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
                let lineWidth = 0;
                let lastSubStrIndex = 0;
                for (let i = 0; i < name.length; i++) {
                    lineWidth += ctx.measureText(name[i]).width;
                    if (lineWidth > maxWidth) {
                        ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY);
                        srartY += wordsHight;
                        lineWidth = 0;
                        lastSubStrIndex = i;
                    }
                    if (i == name.length - 1) {
                        ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY);
                    }
                }
            },
        }
    }
</script>

<style scoped>
   .imgBox{
     width: 80%;
     height: auto;
     padding:30rpx;
     box-sizing: border-box;
     background-color: #fff;
     margin:0 auto;
     text-align: center;
     color: #508CEE;
     position: relative;
     margin-bottom: 20rpx;
   }
   .header{
     width: 245rpx;
     height: 245rpx;
     position: absolute;
     top:241rpx;
     left:177rpx;
     border-radius: 50%;
   }
   .imgBox p{
     margin-bottom: 30rpx;
   }
  .imgBox .codeImg{
    width: 500rpx;
    height: 500rpx;
  }
</style>
